package com.draven.controller;

import com.draven.annotation.Log;
import com.draven.common.Result;
import com.draven.entity.FileInfo;
import com.draven.service.FileService;
import com.draven.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 文件控制器
 */
@RestController
@RequestMapping("/file")
@Validated
public class FileController {

    @Autowired
    private FileService fileService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @Log(module = "文件管理", operationType = "UPLOAD", description = "上传文件")
    public Result<FileInfo> uploadFile(
            HttpServletRequest request,
            @NotNull(message = "文件不能为空") @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false, defaultValue = "0") Integer isPublic) {
        
        Long userId = (Long) request.getAttribute("userId");
        FileInfo fileInfo = fileService.uploadFile(file, userId, categoryId, isPublic);
        return Result.success(fileInfo);
    }

    /**
     * 批量上传文件
     */
    @PostMapping("/batchUpload")
    @Log(module = "文件管理", operationType = "BATCHUPLOAD", description = "批量上传文件")
    public Result<List<FileInfo>> batchUploadFiles(
            HttpServletRequest request,
            @NotNull(message = "文件不能为空") @RequestParam("files") MultipartFile[] files,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false, defaultValue = "0") Integer isPublic) {
        
        Long userId = (Long) request.getAttribute("userId");
        List<FileInfo> fileInfoList = fileService.batchUploadFiles(files, userId, categoryId, isPublic);
        return Result.success(fileInfoList);
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{id}")
    @Log(module = "文件管理", operationType = "DOWNLOAD", description = "下载文件")
    public void downloadFile(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable Long id) {
        
        Long userId = (Long) request.getAttribute("userId");
        fileService.downloadFile(id, userId, response);
    }

    /**
     * 预览文件
     */
    @GetMapping("/preview/{id}")
    public void previewFile(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable Long id,
            @RequestParam(required = false) String token) {
        
        Long userId = null;
        
        // 尝试从请求属性中获取用户ID
        Object userIdAttr = request.getAttribute("userId");
        if (userIdAttr != null) {
            userId = (Long) userIdAttr;
        } 
        // 如果请求属性中没有用户ID，但提供了token，则从token中获取
        else if (token != null && !token.isEmpty()) {
            try {
                userId = jwtUtil.getUserIdFromToken(token);
            } catch (Exception e) {
                // Token无效，返回401错误
                response.setStatus(401);
                return;
            }
        }
        
        // 如果没有获取到用户ID，返回401错误
        if (userId == null) {
            response.setStatus(401);
            return;
        }
        
        fileService.previewFile(id, userId, response);
    }

    /**
     * 获取文件信息
     */
    @GetMapping("/info/{id}")
    public Result<FileInfo> getFileInfo(
            HttpServletRequest request,
            @PathVariable Long id) {
        
        Long userId = (Long) request.getAttribute("userId");
        FileInfo fileInfo = fileService.getFileInfo(id, userId);
        if (fileInfo == null) {
            return Result.error(404, "文件不存在或无权限访问");
        }
        return Result.success(fileInfo);
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/delete/{id}")
    @Log(module = "文件管理", operationType = "DELETE", description = "删除文件")
    public Result<Void> deleteFile(
            HttpServletRequest request,
            @PathVariable Long id) {
        
        Long userId = (Long) request.getAttribute("userId");
        boolean result = fileService.deleteFile(id, userId);
        return result ? Result.success() : Result.error("删除文件失败");
    }

    /**
     * 批量删除文件
     */
    @DeleteMapping("/batchDelete")
    public Result<List<Long>> batchDeleteFiles(
            HttpServletRequest request,
            @RequestBody List<Long> ids) {
        
        Long userId = (Long) request.getAttribute("userId");
        List<Long> successIds = fileService.batchDeleteFiles(ids, userId);
        return Result.success(successIds);
    }

    /**
     * 获取文件列表
     */
    @GetMapping("/list")
    public Result<List<FileInfo>> getFileList(
            HttpServletRequest request,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String fileType,
            @RequestParam(required = false) String keyword) {
        
        Long userId = (Long) request.getAttribute("userId");
        List<FileInfo> fileInfoList = fileService.getFileList(userId, categoryId, fileType, keyword);
        return Result.success(fileInfoList);
    }

    /**
     * 更新文件信息
     */
    @PutMapping("/update")
    public Result<Void> updateFileInfo(
            HttpServletRequest request,
            @RequestParam Long id,
            @RequestParam(required = false) String originalName,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Integer isPublic) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        FileInfo fileInfo = new FileInfo();
        fileInfo.setId(id);
        fileInfo.setUserId(userId);
        
        if (originalName != null) {
            fileInfo.setOriginalName(originalName);
        }
        
        if (categoryId != null) {
            fileInfo.setCategoryId(categoryId);
        }
        
        if (isPublic != null) {
            fileInfo.setIsPublic(isPublic);
        }
        
        boolean result = fileService.updateFileInfo(fileInfo);
        return result ? Result.success() : Result.error("更新文件信息失败");
    }

    /**
     * 获取文件统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getFileStats(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        Map<String, Object> stats = fileService.getFileStats(userId);
        return Result.success(stats);
    }
} 